import { ref, computed } from 'vue';

const BOARD_WIDTH = 10;
const BOARD_HEIGHT = 20;

const SHAPES = [
  { shape: [[1, 1, 1, 1]], color: '#00f0f0' }, // I - Cyan
  { shape: [[1, 1], [1, 1]], color: '#f0f000' }, // O - Yellow
  { shape: [[1, 1, 1], [0, 1, 0]], color: '#a000f0' }, // T - Purple
  { shape: [[1, 1, 1], [1, 0, 0]], color: '#f0a000' }, // L - Orange
  { shape: [[1, 1, 1], [0, 0, 1]], color: '#0000f0' }, // J - Blue
  { shape: [[1, 1, 0], [0, 1, 1]], color: '#00f000' }, // S - Green
  { shape: [[0, 1, 1], [1, 1, 0]], color: '#f00000' }, // Z - Red
];

interface BoardCell {
  filled: boolean;
  color: string;
}

export function useTetris() {
  const board = ref<BoardCell[][]>(Array(BOARD_HEIGHT).fill(0).map(() => 
    Array(BOARD_WIDTH).fill(null).map(() => ({ filled: false, color: '' }))
  ));
  const currentPiece = ref<boolean[][]>([]);
  const currentColor = ref('');
  const nextPiece = ref<boolean[][]>([]);
  const nextColor = ref('');
  const currentPosition = ref({ x: 0, y: 0 });
  const score = ref(0);
  const level = ref(1);
  const lines = ref(0);
  const gameOver = ref(false);
  const isPaused = ref(false);
  const difficulty = ref('normal');
  let gameInterval: number;

  const createEmptyBoard = () => {
    return Array(BOARD_HEIGHT).fill(0).map(() => 
      Array(BOARD_WIDTH).fill(null).map(() => ({ filled: false, color: '' }))
    );
  };

  const getRandomShape = () => {
    const randomPiece = SHAPES[Math.floor(Math.random() * SHAPES.length)];
    return {
      shape: randomPiece.shape.map(row => [...row].map(cell => Boolean(cell))),
      color: randomPiece.color
    };
  };

  const spawnPiece = () => {
    if (nextPiece.value.length === 0) {
      const piece = getRandomShape();
      nextPiece.value = piece.shape;
      nextColor.value = piece.color;
    }
    
    currentPiece.value = nextPiece.value;
    currentColor.value = nextColor.value;
    
    const nextPieceData = getRandomShape();
    nextPiece.value = nextPieceData.shape;
    nextColor.value = nextPieceData.color;
    
    currentPosition.value = {
      x: Math.floor((BOARD_WIDTH - currentPiece.value[0].length) / 2),
      y: 0
    };

    if (checkCollision()) {
      gameOver.value = true;
      clearInterval(gameInterval);
    }
  };

  const checkCollision = (offsetX = 0, offsetY = 0) => {
    return currentPiece.value.some((row, y) =>
      row.some((cell, x) => {
        if (!cell) return false;
        const newX = x + currentPosition.value.x + offsetX;
        const newY = y + currentPosition.value.y + offsetY;
        return (
          newX < 0 ||
          newX >= BOARD_WIDTH ||
          newY >= BOARD_HEIGHT ||
          board.value[newY]?.[newX].filled
        );
      })
    );
  };

  const mergePiece = () => {
    currentPiece.value.forEach((row, y) => {
      row.forEach((cell, x) => {
        if (cell) {
          const boardY = y + currentPosition.value.y;
          const boardX = x + currentPosition.value.x;
          if (boardY >= 0 && boardY < BOARD_HEIGHT && boardX >= 0 && boardX < BOARD_WIDTH) {
            board.value[boardY][boardX] = { filled: true, color: currentColor.value };
          }
        }
      });
    });
  };

  const moveLeft = () => {
    if (!isPaused.value && !checkCollision(-1, 0)) {
      currentPosition.value.x--;
    }
  };

  const moveRight = () => {
    if (!isPaused.value && !checkCollision(1, 0)) {
      currentPosition.value.x++;
    }
  };

  const moveDown = () => {
    if (isPaused.value) return false;
    if (!checkCollision(0, 1)) {
      currentPosition.value.y++;
      return true;
    }
    mergePiece();
    clearLines();
    spawnPiece();
    return false;
  };

  const rotate = () => {
    if (isPaused.value) return;
    const rotated = currentPiece.value[0].map((_, i) =>
      currentPiece.value.map(row => row[row.length - 1 - i])
    );
    const previousPiece = currentPiece.value;
    currentPiece.value = rotated;
    
    if (checkCollision()) {
      currentPiece.value = previousPiece;
    }
  };

  const clearLines = () => {
    let clearedLines = 0;
    for (let y = BOARD_HEIGHT - 1; y >= 0; y--) {
      if (board.value[y].every(cell => cell.filled)) {
        board.value.splice(y, 1);
        board.value.unshift(Array(BOARD_WIDTH).fill(null).map(() => ({ filled: false, color: '' })));
        clearedLines++;
        y++;
      }
    }
    
    if (clearedLines > 0) {
      lines.value += clearedLines;
      score.value += clearedLines * 100 * level.value;
      level.value = Math.floor(lines.value / 10) + 1;
    }
  };

  const togglePause = () => {
    isPaused.value = !isPaused.value;
    if (isPaused.value) {
      clearInterval(gameInterval);
    } else {
      startGameInterval();
    }
  };

  const setDifficulty = (newDifficulty: string) => {
    difficulty.value = newDifficulty;
    if (!gameOver.value && !isPaused.value) {
      clearInterval(gameInterval);
      startGameInterval();
    }
  };

  const getDifficultySpeed = () => {
    const baseSpeed = 1000;
    const speeds = {
      easy: baseSpeed * 1.5,
      normal: baseSpeed,
      hard: baseSpeed * 0.6
    };
    return speeds[difficulty.value as keyof typeof speeds] / level.value;
  };

  const startGameInterval = () => {
    if (gameInterval) {
      clearInterval(gameInterval);
    }
    gameInterval = setInterval(() => {
      moveDown();
    }, getDifficultySpeed()) as unknown as number;
  };

  const startGame = () => {
    board.value = createEmptyBoard();
    nextPiece.value = [];
    score.value = 0;
    level.value = 1;
    lines.value = 0;
    gameOver.value = false;
    isPaused.value = false;
    spawnPiece();
    startGameInterval();
  };

  const displayBoard = computed(() => {
    const display = board.value.map(row => row.map(cell => ({ ...cell })));
    
    if (!gameOver.value) {
      currentPiece.value.forEach((row, y) => {
        row.forEach((cell, x) => {
          if (cell) {
            const boardY = y + currentPosition.value.y;
            const boardX = x + currentPosition.value.x;
            if (boardY >= 0 && boardY < BOARD_HEIGHT && boardX >= 0 && boardX < BOARD_WIDTH) {
              display[boardY][boardX] = { filled: true, color: currentColor.value };
            }
          }
        });
      });
    }
    
    return display;
  });

  return {
    displayBoard,
    nextPiece,
    nextColor,
    score,
    level,
    lines,
    gameOver,
    isPaused,
    difficulty,
    startGame,
    moveLeft,
    moveRight,
    moveDown,
    rotate,
    togglePause,
    setDifficulty
  };
}